var ports = require("../../utils/ports.js")
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pointNum: 0,
    expressTotal: 0,
    orderAmountFreeFare: 0,
    MemberBonusList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var type = options.type;
    if (type == 'cart') {
      that.getCartList()
    } else if (type == 'detail') {
      var goodsShopID = options.id
      var qty = options.qty
      var priceNow = options.realPrice
      var objectFeatureItemName1 = options.objectFeatureItemName1
      var objectFeatureItemID1 = options.objectFeatureItemID1
      that.getGoodsShopDetail(goodsShopID, qty, priceNow, objectFeatureItemID1, objectFeatureItemName1)
    } else {
      wx.showToast({
        title: '订单异常',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1000);
    }
  },
  //地址页面
  toAddress: function () {
    wx.navigateTo({
      url: '../address/address?type=order',
    })
  },
  //确认支付
  paybtn: function () {
    var that = this
    var type = that.data.type //订单类型
    var data = {}
    data.paywayID = app.paywayID
    var address = that.data.address
    if (!address) {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return
    }
    var openid = wx.getStorageSync("USER_OPENID")
    if (!openid) {
      wx.showToast({
        title: '用户信息异常',
        icon: 'none'
      })
      return
    }
    if (that.data.objectFeatureItemID1) {
      data.objectFeatureItemID1 = that.data.objectFeatureItemID1
    }
    if (that.data.memberBonusID) {
      data.memberBonusID = that.data.memberBonusID
    }
    data.contactName = address.contactName
    data.address = address.shengName + address.shiName + address.xianName + address.name
    data.contactPhone = address.phone
    wx.showToast({
      title: '提交中',
      icon: 'loading',
      mask: true
    })
    if (type == 'cart') {
      that.createMemberOrderFromCart(data)
    } else if (type == 'detail') {
      data.qty = that.data.qty
      data.goodsShopID = that.data.goodsShopDetail.id
      that.createMemberOrder(data)
    } else {
      wx.showToast({
        title: '订单异常',
        icon: 'none'
      })
      return
    }
  },
  //红包选择
  onHide: function () { },
  //购物车列表
  getCartList() {
    var that = this
    that.getExpressInfo()
    ports.ModuleCart.getCartList({
      isSelect: 1
    }, that, res => {
      if (res.data.header.code == 0) {
        var goodsList = res.data.body.data[0].goodsList
        var total = 0;
        for (var i = 0; i < goodsList.length; i++) {
          total += goodsList[i].priceTotal
        }
        var realtotal = total + parseInt(that.data.expressTotal)
        if (total >= that.data.orderAmountFreeFare) {
          realtotal = total
          that.setData({
            expressTotal: 0
          })
        }
        that.setData({
          total: total,
          realTotal: realtotal.toFixed(2),
          type: 'cart',
          cartList: res.data.body.data
        })
        that.getMyMemberBonusList()
        //that.getMyStatisticsData()
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //商品详情
  getGoodsShopDetail(goodsShopID, qty, priceNow, objectFeatureItemID1, objectFeatureItemName1) {
    var that = this
    that.getExpressInfo()
    //店铺商品详情
    ports.ModuleGoodsShop.getGoodsShopDetail({
      goodsShopID: goodsShopID,
      type: 2
    }, that, res => {
      if (res.data.header.code == 0) {

        var total = priceNow * qty
        var realtotal = (priceNow * qty) + parseInt(that.data.expressTotal)
        if (total >= that.data.orderAmountFreeFare) {
          realtotal = total
          that.setData({
            expressTotal: 0
          })
        }
        that.setData({
          total: total,
          realTotal: realtotal.toFixed(2),
          qty: qty,
          type: 'detail',
          priceNow: priceNow,
          objectFeatureItemName1: objectFeatureItemName1,
          objectFeatureItemID1: objectFeatureItemID1,
          goodsShopDetail: res.data.body.data
        })
        that.getMyMemberBonusList()
      }
    })
  },
  getExpressInfo() {
    var that = this
    //获取订单运费
    ports.ModuleGoodsShop.getParameterValueByCode({
      code: app.orderFare,
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          expressTotal: res.data.body.data
        })
      }
    })
    //获取包邮信息
    ports.ModuleGoodsShop.getParameterValueByCode({
      code: app.orderAmountFreeFare,
    }, that, res => {
      if (res.data.header.code == 0) {
        that.setData({
          orderAmountFreeFare: res.data.body.data
        })
      }
    })
  },
  //选择红包
  showCoupon(e) {
    const that = this;
    that.setData({
      toggleCoupon: true,
    })
  },
  // 关闭遮罩和选择优惠券
  closeCoupon() {
    const that = this;
    that.setData({
      toggleCoupon: false
    })
  },
  //选择优惠券
  selcoupon(e) {
    var that = this
    var index = e.detail.index; //优惠券下标
    var MemberBonusList = that.data.MemberBonusList; //优惠券列表
    var couponPrice = 0; //优惠券金额
    var toggleCoupon = false; //优惠券弹框
    var useCoupon = false; //是否使用优惠券
    var realTotal = parseFloat(that.data.realTotal) //实际价格
    var memberBonusID = '' //红包id
    var total = parseFloat(that.data.total) //总价格
    var expressTotal = that.data.expressTotal //运费
    if (that.data.expressTotal) {
      expressTotal = parseFloat(that.data.expressTotal)
    }
    for (var i = 0; i < MemberBonusList.length; i++) {
      if (index != i) {
        MemberBonusList[i]._checked = false
      } else {
        if (MemberBonusList[index]._checked) {
          MemberBonusList[index]._checked = false
          couponPrice = 0;
        } else {
          useCoupon = true
          MemberBonusList[index]._checked = true
          couponPrice = MemberBonusList[index].amount
          memberBonusID = MemberBonusList[index].id
        }
      }
    }
    realTotal = total - couponPrice + expressTotal
    that.setData({
      realTotal: realTotal.toFixed(2),
      memberBonusID,
      couponPrice,
      useCoupon,
      toggleCoupon,
      MemberBonusList,
    })
  },
  //不使用
  noused() {
    const that = this;
    that.setData({
      toggleCoupon: false,
    })
  },
  //优惠券列表
  getMyMemberBonusList() {
    var that = this
    var data = {}
    data.pageNumber = 999
    data.status = 1
    ports.ModuleBonus.getMyMemberBonusList(data, that, res => {
      if (res.data.header.code == 0) {
        var MemberBonusList = res.data.body.data.rows
        var realMemberBonusList = []
        var bonusStartPrice = 0;
        for (var i = 0; i < MemberBonusList.length; i++) {
          bonusStartPrice = MemberBonusList[i].bonusStartPrice
          if (bonusStartPrice && parseFloat(bonusStartPrice) <= parseFloat(that.data.total)) {
            realMemberBonusList.push(MemberBonusList[i])
          }
        }
        that.setData({
          MemberBonusList: realMemberBonusList
        })
      }
    })
  },
  
  //会员钱包数据
  getMyStatisticsData() {
    var that = this
    ports.ModuleMember.getMyStatisticsData({}, that, res => {
      if (res.data.header.code == 0) {
        var memberStatistics = res.data.body.memberStatisticsDto
        that.setData({
          pointNum: memberStatistics.point,
          memberStatistics
        })
      }
    })
  },
  //商品详情创建订单
  createMemberOrder(data) {
    var that = this
    ports.ModuleMemberOrder.createMemberOrder(data, that, res => {
      console.log(res)
      if (res.data.header.code == 0) {
        let payData = {}
        payData.memberPaymentID = res.data.body.data;
        payData.openid = wx.getStorageSync("USER_OPENID")
        payData.payWayID = app.paywayID
        payData.body = '购买商品'
        wx.showToast({
          title: '下单成功，支付暂未开放',
          icon: 'none'
        })
        //that.appApplyMemberOrderPay(payData)
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //购物车创建订单
  createMemberOrderFromCart(data) {
    var that = this;
    ports.ModuleMemberOrder.createMemberOrderFromCart(data, that, res => {
      if (res.data.header.code == 0) {
        let payData = {}
        payData.memberPaymentID = res.data.body.data;
        payData.openid = wx.getStorageSync("USER_OPENID")
        payData.payWayID = app.paywayID
        payData.body = '购买商品'
        wx.showToast({
          title: '下单成功，支付暂未开放',
          icon: 'none'
        })
        //that.appApplyMemberOrderPay(payData)
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  },
  //申请订单支付
  appApplyMemberOrderPay(data) {
    var that = this
    ports.ModuleMemberOrder.appApplyMemberOrderPay(data, that, res => {
      if (res.data.header.code == 0) {
        var data = res.data.body;
        wx.requestPayment({
          timeStamp: data.timeStamp,
          nonceStr: data.nonceStr,
          package: data.package,
          signType: data.signType,
          paySign: data.paySign,
          success(res) {
            wx.showToast({
              title: '支付成功',
              icon: 'none',
              mask: true,
              duration: 1000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/order/order',
              })
            }, 1000);
          },
          fail() {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              mask: true,
              duration: 1000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/order/order',
              })
            }, 1000);
          }
        })
      } else {
        wx.showToast({
          title: res.data.header.msg,
          icon: 'none'
        })
      }
    })
  }
})